﻿@namespace Blazorise
@typeparam TItem
@inherits BaseComponent
<CascadingValue Value="@this" IsFixed>
    <div @key="@ElementId" @ref="@ElementRef" id="@ElementId" class="@ClassNames" style="@StyleNames" @ondragenter="@OnDragEnterHandler" @ondragleave="@OnDragLeaveHandler" @ondrop="@OnDropHandler" @attributes="@Attributes">
        @ChildContent

        @if ( !OnlyZone )
        {
            int index = 0;
            var transactionIndex = ParentContainer?.GetTransactionIndex() ?? -1;
            var items = GetItems();

            @if ( AllowReorder )
            {
                @DraggablePreviewFragment(transactionIndex)
            }

            @foreach ( var item in items )
            {
                @DraggableItemFragment((item,index,transactionIndex))

                index++;
            }
        }
    </div>
</CascadingValue>
@code {
    protected RenderFragment<int> DraggablePreviewFragment => transactionIndex => __builder =>
    {
        if ( !items.Any() )
        {
            <div @key="@($"{ElementId}_item_preview_placeholder")" class="@PlaceholderClassBuilder.Class"></div>
        }
        else
        {
            if ( transactionIndex == -1 )
            {
                <div @key="@($"{ElementId}_item_preview_placeholder")" class="@PlaceholderClassBuilder.Class"></div>
            }

            <_Draggable @key="@($"{ElementId}_item_preview")" TItem="TItem" Item="default" ZoneName="@Name" Disabled="true" HideContent="false" Class="draggable-preview-start" />
        }
    };

    protected RenderFragment<(TItem item, int index, int transactionIndex)> DraggableItemFragment => tuple => __builder =>
    {
        var item = tuple.item;
        var index = tuple.index;
        var transactionIndex = tuple.transactionIndex;

        <_Draggable @key="@($"{ElementId}_item_draggable_{index}")" TItem="TItem" Item="@item" ZoneName="@Name" DraggingClass="@GetItemDraggingClass()" Disabled="@GetItemDisabled(item)" DisabledClass="@GetItemDisabledClass()" DragStarted="@OnDragStarted" DragEnded="@OnDragEnded" Index="@index">
            @{
                var renderer = ItemTemplate ?? ParentContainer?.ItemTemplate;
            }

            @if ( renderer is not null )
            {
                @renderer(item)
            }
        </_Draggable>

        if ( transactionIndex == index && !IsOrigin( index ) )
        {
            <div @key="@($"{ElementId}_item_placeholder")" class="@PlaceholderClassBuilder.Class"></div>
        }
    };
}